package com.java.servlet.web.commons;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

@WebServlet(name="ChatServlet", urlPatterns={"/chat/chat.do"},
		loadOnStartup=1)
public class Chat extends HttpServlet {
		/**
		 * 
		 */
		private static final long serialVersionUID = 113880057049845876L;
		static Map<String, List<String>> _chat = new HashMap<String, List<String>>();
		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			req.setCharacterEncoding("UTF-8");
			String action = req.getParameter("action");
			if ("send".equals(action)) {
				String msg = new String(req.getParameter("msg").getBytes("ISO-8859-1"), "UTF-8");
				String uid = (String)req.getSession().getAttribute("user");
				for (String s : _chat.keySet()) {
					if (!s.equals(uid)) {
						synchronized (_chat.get(s)) {
							_chat.get(s).add(uid+" mensage: "+msg);
						}
					}
				}
			} else if ("get".equals(action)) {
				String uid = (String)req.getSession().getAttribute("user");
				if (uid == null){
					resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
				}
				List<String> l = _chat.get(uid);
				try{
					if(l != null){
						synchronized (l) {
							if (l.size() > 0) {
								resp.setCharacterEncoding("UTF-8");
								PrintWriter out = resp.getWriter();
								JSONArray jsna = new JSONArray();
								while (l.size() > 0)
									jsna.add(l.remove(0));

								out.println(jsna);
								out.close();
							}
						}
					}
			}catch(Exception e){
				e.printStackTrace();
				System.out.println("Error synchronized   [ " + e);
			}
			}
		}
		public static Map<String, List<String>> getChatMap () {
			return _chat;
		}
	}